define(function(require, exports, module) {
  var $ = require("$");
  var bootbox = require("bootbox");
  var dtUtil = require('datatableutil');
  require("bootstrap_commonrequire");
  var nav = require("bootstrap_nav");
  var loader = require("./loader/loader");
  require("moment");
  require('daterangepicker.css');
  require('bootstrap-daterangepicker');
  require('select2.css');
  require('select2');

  exports.init = function(param) {

    $(document).ready(function() {
      // 蒙版
      loader.loading("数据加载中，请稍后……");
      // 获取当前页面的json数据
      var alldata={};
      
      // 加载自定义模板-条件区域
      var template = require("./pushfailedcall.tpl");
      var Widget = require("widget");
      var Component = Widget.extend({
        template : template
      });
      new Component({
        renderTo : "queryAreaId"
      });

      
      function getCondition() {
        //获取查询条件
        var app_key = $('#app_key').val();// 应用名称的id
        var callIdentifier = $('#sessionId').val();// 应用名称的id
        var queryStr = "";

        if (app_key != '' && app_key != null) {
          queryStr += ("ta.app_key=" + app_key + ";");
        }
        if (callIdentifier != '' && callIdentifier != null) {
          queryStr += ("tpcr.session_id like '%" + callIdentifier + "%';");
        }
        
        var daterange = daterangeCom.getPickerRange();
        if (daterange) {
          var daterange = daterange.split("/");
          // 只获取起始或截止的那一天的时间，这样可以确保是一天
          var startTime = daterange[0];
          var endTime = daterange[1];
          var startstr = startTime.replace(/-/g, "");// 除去yyyy-MM-dd中的“-”
          var endstr = endTime.replace(/-/g, "");
          queryStr += ("tpcr.end_time BETWEEN '" + startstr + "000000' AND '" + endstr + "235959'" + ";");
        }
        
        return queryStr;
      }
      
      // 初始化日期范围选择控件
      var DateRange = require('daterangeinput');
      var daterangeAttrs = {
        daterangeId : "querydatewrapper_rang",
        label : "日期"
      };
      var daterangeCom = new DateRange({
        attrs : daterangeAttrs,
        renderTo : 'querydatewrapper'
      });
      daterangeCom.setRangeToToday();
      
      //加载表单模板和数据
      var Table = require("table");
      // 查询内容显示
      new Table({
        attrs : {
          id : "data_table",
          isHovered : false,
          isStriped : true,
          isBordered : false
        },
        renderTo : param.divWrapperId
      });
      
      // 信息显示
      var accountinfo_data_table = $('#data_table').dataTable({
        "sDom" : "<'hidden'<'span6'l><'hidden'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
        "bJQueryUI" : false,
        "oLanguage" : {
          "sUrl" : "/business/js/common/table/src/lang/dataTable.cn.txt"
        },
        "sPaginationType" : "bootstrap", // 分页自带两种样式，full_numbers和two_button(默认)
        'bPaginate' : true, // 是否分页
        "bProcessing" : true, // 当datatable获取数据时候是否显示正在处理提示信息。
        "bServerSide" : true, // 指定服务器端分页
        "bDeferRender" : true,
        "bFilter" : true,
        "bSort" : true,
        "bInfo" : true,
        "sAjaxSource" : param.ajaxUrl,
        "iDisplayLength" : DATATABLES_CONFIG.iDisplayLength.DEFAULT, // 默认分页的每页记录数
        "fnServerData" : function(sSource, aoData, fnCallback, oSettings) {
          var queryparam = dtUtil.convert_aoData(aoData);
          
          //拼接where查询条件
          var cond = getCondition();
          if (cond != '' && cond != null) {
            queryparam.q += cond;
          }

          // 添加自己的额外参数
          oSettings.jqXHR = $.ajax({
            "dataType" : 'json',
            "contentType" : "application/json;charset=UTF-8",
            "type" : "GET",
            "url" : sSource,
            "data" : queryparam, // 将请求数据转换为后台要求的JSON格式
            "success" : function(json) {
              if (json.flag == '000000') {
                // 隐藏蒙版
                loader.noloading();
                dtUtil.successCallback(json, aoData, fnCallback);
                // 获取当前页面的json数据
                alldata = json;
              } else {
                oauth2Relogin();
              }
            }
          });

        },
        "aoColumns" : [ {
          "sTitle" : "id",
          "bSortable" : false,
          "mData" : "id",
          "bVisible" : false
        }, {
          "sTitle" : "会话标识",
          "bSortable" : false,
          "mData" : "session_id"
        }, {
          "sTitle" : "应用标识",
          "bSortable" : false,
          "mData" : "app_key"
        }, {
          "sTitle" : "外系统编码",
          "bSortable" : false,
          "mData" : "periphery_code"
        }, {
          "sTitle" : "账号标识",
          "bSortable" : false,
          "mData" : "cust_account",
          "bVisible" : false
        }, {
          "sTitle" : "URL地址",
          "bSortable" : false,
          "mData" : "record_url",
          "mRender" : function(data, type, full) {
            var ret = '';
            if(data != '' && data != null){
              if(data.length <= 20){
                ret += "<div class='myphones'>" + data + "</div>";
              }else{
                ret += "<div class='myphones'>" + data.substr(0,30) + "<br>"+data.substr(30,data.length)+"</div>";
              }
              return ret;
            }
          }
        }, {
          "sTitle" : "备注",
          "bSortable" : false,
          "mData" : "note"
        }, {
          "sTitle" : "备注编码",
          "bSortable" : false,
          "mData" : "code",
          "sWidth" : "10%"
        }, {
          "sTitle" : "推送状态",
          "bSortable" : false,
          "mData" : "status",
          "bVisible" : false,
          "mRender" : function(data, type, full) {
            if (data == "0")
//              return "推送成功";
              return "<div class='fontcir' style='font-size:160%;color:green;margin-left:20px;' title='推送成功'><b>✔</b></div>";
            else if (data == "1")
//              return "推送失败";
              return "<div class='fontcir' style='font-size:160%;color:#ffa500;margin-left:20px;' title='推送失败'><b>×</b></div>";
            else
              return "未知";
          }
        }, {
          "sTitle" : "操作",
          "bSortable" : false,
          "mData" : "status",
          "mRender" : function(data, status, full) {
            if(data != '' && data != null){
              var ret = '<div class="btn-group" style="margin-top: 8px;">';
              // 需要修改下按钮位置处的图标
              ret += '<a href="javascript:void(0);" class="btn icon-refresh contrast" title="话单重推"></a>';
              return ret += '</div>';
            }
            
          }
        } ],
        "fnDrawCallback" : function(oSettings) {
          // 表格绘制完成后，去除width属性，使表格可缩放
          $('#' + oSettings.sTableId).css("width", "");
        }
      });

      
      // 查询按钮
      $('#querybtn').click(function() {
        //蒙版
        loader.loading("数据加载中，请稍后……");
        accountinfo_data_table.fnFilter("");
        return false;
      });

      
      // 操作，话单重推按钮
      $("#data_table tbody").on("click", "tr>td>div>a.icon-refresh", function(e) {
        loader.loading("正在重新推送中，请稍后……");
        var rowNode = this.parentNode.parentNode.parentNode;
        var rowData = accountinfo_data_table.fnGetData(rowNode);
        var formdata2= {
            id : rowData.id
        };
        // 将数据提交到后台
        $.ajax({
          url : "/callStatus/repushCall.do",
          dataType : "json",
          data : "data=" + JSON.stringify(formdata2),
          type : "POST",
          async : true,
          success : function(json) {
            if (json.flag == '000000') {
              loader.noloading();
            } else {
              oauth2Relogin();
            }
          },
          error : function() {
            loader.noloading();
            bootbox.alertTimeout("网络请求失败，请重试！");
          }
        });
        
        // 刷新表单
        setTimeout(function(){
          accountinfo_data_table.fnFilter("");
          }, 4000);
//        accountinfo_data_table.fnFilter("");
        return false;
      });


      // 重置按钮
      $('#restbtn').click(function() {
        //蒙版
        loader.loading("数据加载中，请稍后……");
        $('#app_key').select2("val", "");
        $('#sessionId').val("");
        daterangeCom.setRangeToToday();
        accountinfo_data_table.fnFilter("");
        return false;
      });
      
      // 模态显示
      var ruleinfo = function(context) {
        var pushfailed_init = require("./pushfailedcallmodal");
        if ($("#pushfailed_id").length <= 0)
          $("body").append("<div id='pushfailed_id'></div>");
        pushfailed_init.init({
              "title" : "请选择",
              "renderTo" : "pushfailed_id",
              "details": context
        });
      };

      
      // 一键重推按钮
      $('#pushallbtn').click(function() {
        // 显示模态框
        ruleinfo('您确定要将以下推送失败的话单全部重新推送吗?');
        
        $("#confirmbtn").click(function() {
          // JSON字符串转换为JSON对象
          var data = eval(alldata.data);
          var mylen = data.items.length;
          
          // 判断items中的数据，若存在则继续执行
          if(mylen > 0){
            loader.loading("正在一键推送中，请稍后……");
            $('#my_pushfailed_id').modal('hide');
            //拼接where查询条件
            var cond = getCondition();
            // 将数据提交到后台
            $.ajax({
              url : "/callStatus/repushAllCall.do",
              dataType : "json",
              data : "q=" + cond,
              type : "POST",
              async : true,
              success : function(json) {
                if (json.flag == '000000') {
                  // 刷新表单
//                  accountinfo_data_table.fnFilter("");
                  setTimeout(function(){
                    accountinfo_data_table.fnFilter("");
                    }, 5000);
                  loader.noloading();
                } else if(json.flag == '200000'){
                  alert("有部分话单重新推送失败！");
                  // 刷新表单
                  accountinfo_data_table.fnFilter("");
                  loader.noloading();
                } else {
                  oauth2Relogin();
                }
              },
              error : function() {
                loader.noloading();
                bootbox.alertTimeout("网络请求失败，请重试！");
              }
            });
          }
          
        });
        
        return false;
      });
      

    });
    
  };
});
